package com.tdcy.framework.exception;

import java.io.IOException;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import me.chanjar.weixin.common.exception.WxErrorException;

import org.apache.shiro.authz.AuthorizationException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.web.servlet.HandlerExceptionResolver;
import org.springframework.web.servlet.ModelAndView;

import com.tdcy.framework.util.ExceptionUtils;
import com.tdcy.framework.util.JsonUtils;
import com.tdcy.framework.util.RequestUtils;
import com.tdcy.framework.util.WebUtils;
import com.tdcy.sys.service.bean.LoginInfoBean;
import com.tdcy.sys.util.BusiContextExt;
import com.tdcy.sys.util.log.LogManager;
import com.tdcy.sys.util.log.LogTaskFactory;

public class QuickuHandlerExceptionResolver implements HandlerExceptionResolver {
	private static Logger log = LoggerFactory.getLogger(QuickuHandlerExceptionResolver.class);

	public ModelAndView resolveException(HttpServletRequest request, HttpServletResponse response, Object obj,
			Exception exception) {
		try{
			//记录异常日志
			LoginInfoBean loginInfo =  BusiContextExt.getLoginInfo();
			if(loginInfo!=null){
				LogManager.me().executeLog(LogTaskFactory.exceptionLog(loginInfo.getUserEO(), exception));
			}
		}catch(Exception e){
		}
		
		log.error(exception.toString(), exception);
		String uri  = request.getRequestURI();
		if (WebUtils.isAjax(request) || RequestUtils.isRestRequest(request)) {
			Map jsons = null;
			if (exception instanceof BaseException) {
				jsons = WebUtils.createJSONError(exception);
			}else if (exception instanceof AuthorizationException) {
				jsons = WebUtils.createJSONError("没有权限访问");
			}else if (exception instanceof WxErrorException) {
				jsons = WebUtils.createJSONError(ExceptionUtils.getErrorStr(exception));
			}else {
				if( RequestUtils.isRestRequest(request)){
					jsons = WebUtils.createJSONError(ExceptionUtils.getErrorStr(exception));
				}else{
					jsons = WebUtils.createJSONError("系统异常");
				}
			}

			try {
				response.setStatus(HttpStatus.OK.value());
				response.setContentType(MediaType.APPLICATION_JSON_VALUE);
				//response.setContentType("text/html");
				response.getWriter().write(JsonUtils.toJson(jsons));
				response.getWriter().flush();
				response.getWriter().close();
			} catch (IOException e) {
				log.error("对异常进行JSON转换时出错", e);
				e.printStackTrace();
			}

			return null;
		}
		request.setAttribute("exception", exception.toString());
		request.setAttribute("exceptionStack", exception);

		return new ModelAndView("error");
	}
}
